package com.atguigu.yygh.user.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.helper.JwtHelper;
import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.ConstantWxPropertiesUtils;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/ucenter/wx")
@JsonIgnoreProperties(ignoreUnknown = true)
public class WeiXinApiController {

    @Autowired
    private UserInfoService userInfoService;

    //回调方法
    @GetMapping("callback")
    public String callback(String code,String state){
        System.out.println(code);
        //根据code  和微信id 和秘钥  请求微信固定地址 得到两个值

        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
               ConstantWxPropertiesUtils.WX_OPEN_APP_ID,
                ConstantWxPropertiesUtils.WX_OPEN_APP_SECRET,
                code);

        try {
            String accesstokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo"+accesstokenInfo);
            //从返回字符串获取数据、
            JSONObject jsonObject= JSONObject.parseObject(accesstokenInfo);
            String access_token=jsonObject.getString("access_token");
            String openid=jsonObject.getString("openid");


            //判断数据库是否存在微信扫码人信息 根据openid判断
          UserInfo userInfo=userInfoService.selectWxInfoOpenId(openid);

          if(userInfo == null)
          {
              //使用access_token换取受保护的资源：微信的个人信息
              String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                      "?access_token=%s" +
                      "&openid=%s";
              String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
              String resultInfo = HttpClientUtils.get(userInfoUrl);
              System.out.println("扫码人信息"+resultInfo);

              JSONObject resultUserInfoJson = JSONObject.parseObject(resultInfo);

              //解析用户信息
              String nickname = resultUserInfoJson.getString("nickname");  //昵称
              String headimgurl = resultUserInfoJson.getString("headimgurl");  //头像

               userInfo = new UserInfo();
              userInfo.setName(nickname);
              userInfo.setOpenid(openid);
              userInfo.setStatus(1);
              userInfoService.save(userInfo);

          }


            //返回name和token的字符串
            Map<String, Object> map = new HashMap<>();
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);

            //判断userInfo是否有手机号  如果手机号为空  返回openid
            //如果openid不为空  返回openid时空字符串
            //如果openid不为空 绑定手机号 如果为空则 不需要绑定手机号

            if(StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }

            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);
            return
                    "redirect:" + ConstantWxPropertiesUtils.YYGH_BASE_URL + "/weixin/callback?token="+map.get("token")+"&openid="+map.get("openid")+"&name="+URLEncoder.encode((String) map.get("name"),"utf-8");

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }

    //生成微信扫描二维码 返回二维码需要参数
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result genQrConnect(){

        try {

            Map<String, Object> map = new HashMap<>();
            map.put("appid", ConstantWxPropertiesUtils.WX_OPEN_APP_ID);
            map.put("scope", "snsapi_login");
            String wxOpenRedirectUrl = ConstantWxPropertiesUtils.WX_OPEN_REDIRECT_URL;
            wxOpenRedirectUrl = URLEncoder.encode(wxOpenRedirectUrl,"utf-8");
            map.put("redirect_uri", wxOpenRedirectUrl);
            map.put("state", System.currentTimeMillis() + "");
            return Result.ok(map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;




    }

}
